package com.example.ymm.modules1.service.impl.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.user.DbChatGroup;
import com.example.ymm.modules1.entity.my.user.DbUser;
import com.example.ymm.modules1.mapper.my.user.DbChatGroupMapper;
import com.example.ymm.modules1.service.dd.RobotGroupMessagesService;
import com.example.ymm.modules1.service.dto.DbChatGroupDto;
import com.example.ymm.modules1.service.dto.DbChatGroupQueryCriteria;
import com.example.ymm.modules1.service.dto.DbUserQueryCriteria;
import com.example.ymm.modules1.service.user.DbCardService;
import com.example.ymm.modules1.service.user.DbChatGroupService;
import com.example.ymm.modules1.service.user.DbChatGroupUserService;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Month;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DbChatGroupServiceImpl extends BaseServiceImpl<DbChatGroupMapper, DbChatGroup> implements DbChatGroupService {

    @Autowired
    RobotGroupMessagesService robotGroupMessagesService;

    @Autowired
    DbUserService dbUserService;

    @Autowired
    DbCardService dbCardService;

    @Autowired
    DbChatGroupUserService dbChatGroupUserService;

    @Override
    public TableList<DbChatGroup> list(DbChatGroupQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DbChatGroup> page = new Page<DbChatGroup>(pageDto.getPage(),pageDto.getPageSize());
        baseMapper.selectPage(page, QueryHelpPlus.getPredicate(DbChatGroup.class, criteria));
        TableList<DbChatGroup> tableList=new TableList(page);
        return tableList;
    }

    public List<DbChatGroup> queryAll(DbChatGroupQueryCriteria criteria) {
        List<DbChatGroup> result =baseMapper.selectList(QueryHelpPlus.getPredicate(DbChatGroup.class, criteria));
        return result;
    }

    @Override
    public DbChatGroup createGroupChat(DbChatGroupDto dto) {
        DbChatGroup group=new DbChatGroup();
        BeanUtils.copyProperties(dto,group);

        if(UtilValidate.isNotEmpty(dto.getUseridlist())){
            String[] split = dto.getUseridlist().split(",");
            group.setUserIdLists(Arrays.asList(split));
        }
        JSONObject groupChat = robotGroupMessagesService.createGroupChat(group);
        if(UtilValidate.isNotEmpty(groupChat)){
            group.setOpenConversationId(groupChat.getString("openConversationId"));
            group.setChatid(groupChat.getString("chatid"));
            saveOrUpdate(group);
        }

        return group;
    }

    @Override
    public DbChatGroup editFn(DbChatGroupDto dto) {
        DbChatGroup group=new DbChatGroup();
        BeanUtils.copyProperties(dto,group);
        DbChatGroup oldGroup = getById(group.getOpenConversationId());
        if(!group.getName().equals(oldGroup.getName())
        ||!group.getOwner().equals(oldGroup.getOwner())){
            //修改群名称或群主
            dto.setChatid(oldGroup.getChatid());

            robotGroupMessagesService.editGroupChat(dto);
        }
        saveOrUpdate(group);
        return group;
    }

    @Override
    public List<DbUser> queryGroupChatUsers(String chatid) {
        JSONObject jsonObject = robotGroupMessagesService.queryGroupChatUsers(chatid);
        List<DbUser> dbUsers=new ArrayList<>();
        if(UtilValidate.isNotEmpty(jsonObject)){
            List<String> ids=new ArrayList<>();
            JSONArray useridlist = jsonObject.getJSONArray("useridlist");
            for (int i = 0; i < useridlist.size(); i++) {
                String userId = useridlist.getString(i);
                ids.add(userId);
            }
            DbUserQueryCriteria queryCriteria=new DbUserQueryCriteria();
            queryCriteria.setUserId(ids);
            queryCriteria.setIsRead(0);
            dbUsers = dbUserService.queryAll(queryCriteria);
        }
        return dbUsers;
    }

    @Override
    public DbChatGroup queryGroupChatInfo(String openConversationId) {
        DbChatGroup chatGroup = getById(openConversationId);
        DbUser ownerUser = dbUserService.getById(chatGroup.getOwner());
        chatGroup.setOwner_name(ownerUser.getUserName());
        if(UtilValidate.isNotEmpty(chatGroup.getUseridlist())){
            String[] split = chatGroup.getUseridlist().split(",");
            List<String> list = Arrays.asList(split);
            DbUserQueryCriteria userQueryCriteria=new DbUserQueryCriteria();
            userQueryCriteria.setUserId(list);
            List<DbUser> dbUsers = dbUserService.queryAll(userQueryCriteria);
            List<String> names=new ArrayList<>();
            dbUsers.forEach(r->{
                names.add(r.getUserName());
            });
            chatGroup.setUseridlist_name(String.join(",",names));
        }
        String chatid=chatGroup.getChatid();
//        JSONObject jsonObject = robotGroupMessagesService.queryGroupChatUsers(chatid);
//        String name = jsonObject.getString("name");
//        chatGroup.setName(name);
//        saveOrUpdate(chatGroup);
        return chatGroup;
    }

    @Override
    public void sendGroupListMessage() {
        DbChatGroupQueryCriteria criteria=new DbChatGroupQueryCriteria();
//        criteria.setState(1);
        List<DbChatGroup> dbChatGroups = queryAll(criteria);
        dbChatGroups.forEach(r->{

            try{
                sendGroupMessage(r);
//                robotGroupMessagesService.send(r.getOpenConversationId(),text);
                robotGroupMessagesService.sendLink(r.getOpenConversationId());
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        });
    }

    @Override
    public void sendGroupLinkMessage() {
        DbChatGroupQueryCriteria criteria=new DbChatGroupQueryCriteria();
//        criteria.setState(1);
        List<DbChatGroup> dbChatGroups = queryAll(criteria);
        dbChatGroups.forEach(r->{
//            sendGroupMessage(r);
            try{
                robotGroupMessagesService.sendLink(r.getOpenConversationId());
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        });
    }

    @Override
    public List<DbUser> testSend(String openConversationId) {
        try{
//            String text="请各位负责人自行邀请读书成员进群，点击下方链接进入读书打卡小程序 或者 可在 钉钉>工作台>全员>读书打卡，找到读书打卡小程序。进入搜索相应书本选择相应章节开始阅读，阅读完毕将笔记分享至读书打卡群，次日8.30自动汇总打卡。";
//            robotGroupMessagesService.send(openConversationId,text);
//            robotGroupMessagesService.sendLink(openConversationId);
            DbChatGroup group=getById(openConversationId);
            List<DbUser> dbUsers = queryGroupChatUsers(group.getChatid());
//            List<DbUser> dbUsers = new ArrayList<>();
//            DbUser byId = dbUserService.getById("2363192520970306");
//            dbUsers.add(byId);
            List<DbUser> users = dbCardService.countUserCardByGroup(dbUsers,group);
            return users;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    @Override
    public void sendGroupMessage(DbChatGroup group) {
        List<DbUser> dbUsers = queryGroupChatUsers(group.getChatid());
        try {
            Thread thread = new Thread(()->{
                dbChatGroupUserService.syncGroupUser(group,dbUsers);
            });
            thread.start();
        }catch (Exception e){
            log.error("-同步群-人员 关联关系失败:"+e.getMessage(),e);
        }


        String templatePrefix = group.getTemplatePrefix();
        String[] split = group.getStartDate().split("-");
        String startDate_str=split[0]+"年"+split[1]+"月"+split[2]+"日";
        templatePrefix=templatePrefix.replaceAll("#startDate",startDate_str);
        // 计算时间长度
        Date start = DateKit.dateFormat(group.getStartDate() + " 08:30:00");
        Date now =new Date();

        int dateNum = DateKit.dateDiff(1, start, now);
        templatePrefix=templatePrefix.replaceAll("#dateNum",(dateNum+1)+"");

        //获取当前月份
        YearMonth yearMonth = YearMonth.now();
        Month month = yearMonth.getMonth();
        int monthStr = month.getValue();
        int startStr = 1;
        int endStr = month.maxLength();
        templatePrefix=templatePrefix.replaceAll("#month",monthStr+"");

        if(templatePrefix.contains("#start")&&templatePrefix.contains("#end")){
//            if(group.getTotalType().equals(2)){
//
//            }else{
//                templatePrefix=templatePrefix.replaceAll("#month月#start日～#end日","");
//            }
            templatePrefix=templatePrefix.replaceAll("#start",startStr+"");
            templatePrefix=templatePrefix.replaceAll("#end",endStr+"");
        }

        String templateSuffix = group.getTemplateSuffix();
        String nameSuffix = group.getNameSuffix();
        if(UtilValidate.isEmpty(nameSuffix)){
            nameSuffix="";
        }
        StringBuffer temple=new StringBuffer(templatePrefix+"\n");
        List<DbUser> users = dbCardService.countUserCardByGroup(dbUsers,group);
        for (int i = 0; i < users.size(); i++) {
            DbUser dbUser = users.get(i);
            int index=i+1;
            String str=index+"."+dbUser.getUserName()+"（"+dbUser.getCardNums()+"）";
            if(UtilValidate.isNotEmpty(nameSuffix)){
                str+=nameSuffix;
            }
            temple.append(str+"\n");
        }
        temple.append(templateSuffix+"\n");
        try {
            log.info("--发送群聊:"+group.getOpenConversationId());
            robotGroupMessagesService.send(group.getOpenConversationId(),temple.toString());
        }catch (Exception e){
            log.error("发送群消息失败",e);
            throw new YmException(e.getMessage());
        }

    }


    @Override
    public void sendGroupNotice(String notice) {
        List<DbChatGroup> dbChatGroups = queryAll(null);
        for(DbChatGroup chatGroup:dbChatGroups){
            try {
                robotGroupMessagesService.send(chatGroup.getOpenConversationId(),notice);
            }catch (Exception e){
                log.error("发送群消息失败",e);
                throw new YmException(e.getMessage());
            }
        }
    }

    @Override
    public void sendGroupNoticeImg(String img) {
        List<DbChatGroup> dbChatGroups = queryAll(null);
        for(DbChatGroup chatGroup:dbChatGroups){
            try {
                robotGroupMessagesService.sendImg(chatGroup.getOpenConversationId(),img);
            }catch (Exception e){
                log.error("发送群消息失败",e);
                throw new YmException(e.getMessage());
            }
        }
    }
}
